package com.lkx.farmershop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkx.farmershop.common.api.ApiResult;
import com.lkx.farmershop.mapper.TagMapper;
import com.lkx.farmershop.model.dto.QueryObj;
import com.lkx.farmershop.model.entity.*;
import com.lkx.farmershop.model.vo.GroupVo;
import com.lkx.farmershop.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (Tag)表服务实现类
 *
 * @author makejava
 * @since 2025-01-25 15:01:17
 */
@Service("tagService")
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Autowired
    private HotTagsService hotTagsService;
    @Autowired
    private TuanService tuanService;
    @Autowired
    private IFarmerService farmerService;
    @Autowired
    private TuanImageService tuanImageService;

    @Autowired
    private TagService tagService;
    @Autowired
    private TagTuanService tagTuanService;
    @Autowired
    private UserWordService userWordService;

    @Override
    public ApiResult<List<String>> getHotTags() {
        List<HotTags> hotTags = hotTagsService.list();
        if (hotTags == null || hotTags.isEmpty()) {
            return ApiResult.failed();
        }
        List<String> hotTagNames = hotTags.stream().map(hotTag -> {
            Tag tag = getById(hotTag.getTagId());
            return tag.getTagname();
        }).collect(Collectors.toList());
        return ApiResult.success(hotTagNames);
    }

    @Override
    public ApiResult<List<String>> seachByQuery(String query) {
        if (StrUtil.isBlank(query)) {
            // 查询条件为空
            return ApiResult.failed("请输入查询条件！");
        }

        List<String> tagNameList = lambdaQuery()
                .like(Tag::getTagname, query)  // 搜索条件
                .orderByDesc(Tag::getUsedCount)   // 根据使用次数降序
                .last("limit 10")   // 只查10条
                .list()
                .stream()
                .map(Tag::getTagname) //获取商品名称
                .collect(Collectors.toList());

        return ApiResult.success(tagNameList);
    }

    @Override
    public ApiResult<List<GroupVo>> searchByName(QueryObj queryObj) {
        //添加用户关键词
        addUserWord2(queryObj);

        //从组团的标题和内容查找
        List<GroupVo> groupVoList = tuanService.lambdaQuery()
                .like(Tuan::getTuanTitle, queryObj.getTheKeyWord())  // 搜索条件
                .or()
                .like(Tuan::getTuanDetail, queryObj.getTheKeyWord())
                .orderByDesc(Tuan::getSendTime)
                .last("LIMIT " + (queryObj.getPageNum() - 1) * queryObj.getPageSize() + ", " + queryObj.getPageSize())   // 只查10条
                .list()
                .stream()
                .map(this::apply)
                .collect(Collectors.toList());

        return ApiResult.success(groupVoList);
    }

    @Override
    public ApiResult<List<GroupVo>> searchByTag(QueryObj queryObj) {
        //添加用户关键词
        addUserWord2(queryObj);

        List<GroupVo> groupVoList = new ArrayList<>();
            //从标签查找
            Tag tag = lambdaQuery().eq(Tag::getTagname, queryObj.getTheKeyWord()).one();
            if (tag != null) {
                //获取标签的组团

                List<Long> tuanIds = tagTuanService.lambdaQuery()
                        .eq(TagTuan::getTagId, tag.getId())
                        .orderByAsc(TagTuan::getId)
                        .last("LIMIT " + (queryObj.getPageNum() - 1) * queryObj.getPageSize() + ", " + queryObj.getPageSize())
                        .list()
                        .stream()
                        .map(TagTuan::getTuanId)
                        .collect(Collectors.toList());
                //获取组团信息
                if (!tuanIds.isEmpty()) {
                    groupVoList = tuanService.lambdaQuery()
                            .in(Tuan::getTuanId, tuanIds)
                            .orderByDesc(Tuan::getSendTime)
                            .list()
                            .stream()
                            .map(this::apply)
                            .collect(Collectors.toList());

                }
            }
        return ApiResult.success(groupVoList);
    }

    private void addUserWord2(QueryObj queryObj) {
        Long userId = queryObj.getUserId();
        String name = queryObj.getTheKeyWord();

        if (queryObj.getUserId() != null){
            UserWord one = userWordService.getOne(new LambdaQueryWrapper<UserWord>()
                    .eq(UserWord::getUserId, userId)
                    .eq(UserWord::getWord, name));
            if ( one == null) {
                UserWord userWord = new UserWord(userId, name, 1);
                userWordService.save(userWord);
            }else {
                userWordService.update(new LambdaUpdateWrapper<UserWord>()
                        .eq(UserWord::getUserId, userId)
                        .eq(UserWord::getWord, name)
                        .setSql("count = count + 1"));
            }
        }
    }

    @Override
    public ApiResult<List<String>> getUserTag(Long userId) {
        Farmer user = farmerService.lambdaQuery().eq(Farmer::getFarmerId, userId).one();
        if (user != null) {
            String MyTag = user.getMyTag();
            List<String> tagList = new ArrayList<>();
            if (MyTag != null) {
                String[] tags = MyTag.split(",");
                Collections.addAll(tagList, tags);
            }
            return ApiResult.success(tagList);
        } else {
            return ApiResult.failed("请先登录");
        }
    }

    @Override
    public ApiResult<String> updateTags(Long userId, List<String> tags) {
        Farmer user = farmerService.lambdaQuery().eq(Farmer::getFarmerId, userId).one();
        if (user != null) {
            StringBuilder sb = new StringBuilder();
            for (String tag : tags) {
                sb.append(tag).append(",");
            }
            user.setMyTag(sb.toString());
            if (farmerService.updateById(user)) {
                return ApiResult.success("修改标签成功");
            } else {
                return ApiResult.failed("修改标签失败");
            }
        }
        return ApiResult.failed("请先登录");
    }


    private GroupVo apply(Tuan tuan) {
        GroupVo groupVo = new GroupVo();
        //设置组团信息
        BeanUtils.copyProperties(tuan, groupVo);
        //获取该组团的用户头像与昵称
        LambdaQueryWrapper<Farmer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Farmer::getFarmerId, tuan.getUserId());
        Farmer user = farmerService.getOne(queryWrapper);
        groupVo.setName(user.getName());
        groupVo.setAvatar(user.getAvatar());
        //获取前三张图片
        LambdaQueryWrapper<TuanImage> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(TuanImage::getTuanId, tuan.getTuanId());
        List<TuanImage> imageList = tuanImageService.list(qw2);
        if (imageList != null && !imageList.isEmpty()) {
            List<String> threeImages = imageList.stream().map(TuanImage::getImageUrl).limit(3).collect(Collectors.toList());
            groupVo.setThreeImages(threeImages);
        } else {
            groupVo.setThreeImages(new ArrayList<>());
        }
        return groupVo;
    }
}